from auth import AuthHandler
from database import SessionLocal
from models.notification import RefreshToken
from models import User
from datetime import datetime

# 模拟refresh token接口的完整验证过程
db = SessionLocal()
try:
    # 获取最新的未撤销的refresh token
    latest_token = db.query(RefreshToken).filter(
        RefreshToken.is_revoked == False
    ).order_by(RefreshToken.created_at.desc()).first()
    
    if latest_token:
        token = latest_token.token
        print(f"=== 模拟refresh接口调用 ===")
        print(f"Token: {token}")
        
        # 步骤1: 验证JWT token
        print("\n1. 验证JWT token...")
        try:
            payload = AuthHandler.verify_token(token)
            username = payload.get("sub")
            token_type = payload.get("type")
            
            print(f"   - username: {username}")
            print(f"   - token_type: {token_type}")
            
            if username is None or token_type != "refresh":
                print("❌ JWT验证失败: username为空或token_type不正确")
            else:
                print("✅ JWT验证成功")
                
        except Exception as e:
            print(f"❌ JWT验证异常: {e}")
        
        # 步骤2: 检查数据库中的token记录
        print("\n2. 检查数据库中的token记录...")
        refresh_token_record = db.query(RefreshToken).filter(
            RefreshToken.token == token,
            RefreshToken.is_revoked == False
        ).first()
        
        if not refresh_token_record:
            print("❌ 数据库中未找到对应的token记录或token已被撤销")
        else:
            print("✅ 数据库token记录正常")
            print(f"   - user_id: {refresh_token_record.user_id}")
            print(f"   - expires_at: {refresh_token_record.expires_at}")
            print(f"   - is_revoked: {refresh_token_record.is_revoked}")
        
        # 步骤3: 验证用户存在
        print("\n3. 验证用户存在...")
        user = db.query(User).filter(User.username == username).first()
        if not user:
            print("❌ 用户不存在")
        else:
            print("✅ 用户验证成功")
            print(f"   - user_id: {user.id}")
            print(f"   - username: {user.username}")
            print(f"   - status: {user.status}")
            
        print("\n✅ 所有验证步骤都通过! refresh接口应该返回新的tokens")
        
    else:
        print("没有找到有效的refresh token")
        
finally:
    db.close()